<template>
  <div>
    <el-dialog
      title="新增消费"
      :visible.sync="addGoodVis"
      width="1300px"
      @close="addGoodCancle"
      class=""
    >
      <div class="add">
        <el-row :gutter="24">
          <el-col :span="16">
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="项目消费" name="0">
                <div class="item-list" v-loading="shopItemLoading">
                  <el-row class="item-list-row" :gutter="24">
                    <el-col
                      :span="6"
                      v-for="(item, index) in shopItemArray"
                      :key="index"
                    >
                      <div class="item-xf" @click="itemAddOpen(item)">
                        <div class="item-name">{{ item.itemName }}</div>
                        <div class="item-price">￥{{ item.itemPrice }}</div>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-tab-pane>
              <el-tab-pane label="商品消费" name="1">
                <div class="item-list" v-loading="shopProductLoading">
                  <el-row class="item-list-row" :gutter="24">
                    <el-col
                      :span="6"
                      v-for="(item, index) in shopProductArray"
                      :key="index"
                    >
                      <div class="item-xf" @click="goodsAddOpen(item)">
                        <div class="item-name">{{ item.name }}</div>
                        <div class="item-price">￥{{ item.price }}</div>
                      </div>
                    </el-col>
                  </el-row>
                </div>

                <div class="text-left">
                  <pagination
                    :total="shopProductQuery.total"
                    :page.sync="shopProductQuery.pageNo"
                    :limit.sync="shopProductQuery.pageSize"
                    @pagination="getProductAllList"
                  />
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-col>
          <el-col :span="8">
            <div class="right-ck-list">
              <div class="el-table">
                <el-table
                  :data="addGoodItem.serverList"
                  :border="false"
                  height="360px"
                >
                  <el-table-column prop="contentName" label="项目">
                  </el-table-column>
                  <!-- <el-table-column prop="userName" label="技师名称">
                  </el-table-column> -->
                  <el-table-column prop="price" label="单价"> </el-table-column>
                  <el-table-column prop="contentCount" label="数量">
                  </el-table-column>

                  <el-table-column prop="total" label="小计"> </el-table-column>

                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        @click="delServerItem(scope.$index)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div class="right-ck-bootom">
                <div class="ck-price">￥{{ serverTotal }}</div>
                <div>
                  <el-button
                    type="primary"
                    :loading="addGoodLoading"
                    @click="addXfSave"
                    >确定</el-button
                  >
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 添加项目 -->
    <el-dialog
      title="新增消费"
      :visible.sync="addItemVis"
      width="500px"
      @close="addItemCancle"
    >
      <div>
        <el-form
          :model="addItemObj"
          :rules="addItemRules"
          ref="addItemForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            :label="addItemObj.contentType === 'I' ? '项目数量' : '商品数量'"
            prop="contentCount"
          >
            <el-input-number
              v-model="addItemObj.contentCount"
              :min="1"
              :precision="0"
              :step="1"
              label="请选择数量"
              class="w-100 text-left"
              :controls="false"
              :disabled="addItemObj.contentType === 'I'"
            ></el-input-number>
          </el-form-item>
          <el-form-item
            label="服务技师"
            prop="userId"
            v-if="addItemObj.contentType === 'I'"
          >
            <el-select
              v-model="addItemObj.userId"
              placeholder="请选择服务技师"
              filterable
              class="w-100"
              :loading="thArryLoading"
              @change="changeServeTh"
            >
              <el-option
                v-for="item in thArry"
                :key="item.userId"
                :disabled="thids.indexOf(item.userId) >= 0"
                :label="item.nickname"
                :value="item.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="上钟类型"
            prop="clockType"
            v-if="addItemObj.contentType === 'I'"
          >
            <el-select
              v-model="addItemObj.clockType"
              placeholder="请选择上钟类型"
              filterable
              class="w-100"
            >
              <el-option
                v-for="item in clockTypeList"
                :disabled="!!item.disabled"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="销售员工"
            prop="sellUserId"
            v-if="addItemObj.contentType === 'I'"
          >
            <el-select
              v-model="addItemObj.sellUserId"
              placeholder="请选择销售员工"
              filterable
              class="w-100"
            >
              <el-option
                v-for="item in sellUserIdList"
                :disabled="!!item.disabled"
                :key="item.userId"
                :label="item.nickname"
                :value="item.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addItemCancle">取消</el-button>
        <el-button type="primary" :loading="addItemLoading" @click="addItemSave"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  itemAllList,
  getProductList,
  getStoreUser,
} from "@/api/business/BusinessIndex";

export default {
  props: {
    filterUser: {
      type: String,
      default: "",
    },
  },
  name: "EryuoaStoreFrontendConsume",

  data() {
    return {
      addItemLoading: false,
      addItemVis: false,
      serverTotal: "0.00",
      addGoodVis: false,
      addGoodLoading: false,
      activeName: "0",
      shopProductArray: [],
      shopProductLoading: false,
      shopProductQuery: {
        pageNo: 1,
        pageSize: 20,
        total: 0,
      },
      addItemObj: {
        sellUserId: "",
        clockType: "",
        contentCount: 1,
        contentId: "",
        contentType: "",
        orderId: "",
        userId: "",
      },
      shopItemLoading: false,
      shopItemArray: [],
      settleAccountsObj: {
        moneyMember: 0,
        moneyPos: 0,
        moneyRmb: 0,
        moneyWx: 0,
        moneyZfb: 0,
        orderId: "",
        payList: [],
      },

      addItemRules: {
        userId: [
          { required: true, message: "请选择服务技师", trigger: "change" },
        ],

        contentCount: [
          { required: true, message: "请输入数量", trigger: "change" },
        ],

        clockType: [
          { required: true, message: "请选择上钟类型", trigger: "change" },
        ],
        sellUserId: [
          { required: true, message: "请选择销售员工", trigger: "change" },
        ],
      },
      addGoodItem: {
        // orderId: "",
        serverList: [],
      },

      thArry: [],
      orderId: "",
      sellUserIdList: [], // 销售员工
      thids: [],
    };
  },

  mounted() {},

  watch: {
    "addGoodItem.serverList": {
      handler: function (newVal, oldVal) {
        console.log("1", newVal);
        // console.log(oldVal);
        let ids = [];
        for (let i = 0; i < newVal.length; i++) {
          let item = newVal[i];
          if (item.contentType === "I") {
            ids.push(item.userId);
          }
        }
        this.thids = ids;
      },
      deep: true,
    },
  },

  methods: {
    // 销售员工
    getsellUserId() {
      getStoreUser({})
        .then((res) => {
          const { code, data } = res;
          if (code === 0) {
            this.sellUserIdList = data;
          }
        })
        .catch((err) => {});
    },

    getTharry(itemId) {
      this.thArryLoading = true;
      getStoreUser({
        labelCode: "A",
        itemId: itemId,
        orderId: this.addGoodItem.orderId,
        filterUser: !!this.filterUser ? this.filterUser : undefined,
      })
        .then((res) => {
          this.thArryLoading = false;
          const { code, data } = res;
          if (code === 0) {
            let thArry = [];
            let thArryObj = {};
            for (let index = 0; index < data.length; index++) {
              const item = data[index];
              thArry.push(item);
              thArryObj[item.userId] = item;
            }
            this.thArry = thArry;
            this.thArryObj = thArryObj;
          }
        })
        .catch((err) => {
          this.thArryLoading = false;
        });
    },

    delServerItem(index) {
      this.addGoodItem.serverList.splice(index, 1);
      this.jishuanTotal();
    },

    jishuanTotal() {
      const serverList = JSON.parse(
        JSON.stringify(this.addGoodItem.serverList)
      );

      let total = 0;
      for (let i = 0; i < serverList.length; i++) {
        let item = serverList[i];
        total += Number(item.total);
      }
      this.serverTotal = total.toFixed(2);
    },
    addItemSave() {
      if (this.addItemLoading) {
        return false;
      }

      this.$refs["addItemForm"].validate((valid) => {
        if (valid) {
          const addItemObj = JSON.parse(JSON.stringify(this.addItemObj));
          this.itemOrItemPushList({
            userName: !!addItemObj.userId
              ? this.thArryObj[addItemObj.userId].nickname
              : "",
            ...addItemObj,
          });
          this.addItemCancle();
        } else {
          return false;
        }
      });
    },

    itemOrItemPushList(item) {
      const serverList = JSON.parse(
        JSON.stringify(this.addGoodItem.serverList)
      );

      const ids = serverList.map((item) => {
        return item.contentId;
      });

      let curIndex = ids.indexOf(item.contentId);
      let havItem = {};
      if (curIndex > -1) {
        havItem = JSON.parse(
          JSON.stringify(this.addGoodItem.serverList[curIndex])
        );
      }

      if (
        (curIndex > -1 &&
          havItem.userId === item.userId &&
          havItem.clockType === item.clockType &&
          havItem.contentType === "I") ||
        (curIndex > -1 && havItem.contentType === "P")
      ) {
        havItem.contentCount =
          Number(havItem.contentCount) + Number(item.contentCount);
        havItem.total = (havItem.price * havItem.contentCount).toFixed(2);
        this.$set(this.addGoodItem.serverList, curIndex, havItem);
      } else {
        item.total = (item.price * item.contentCount).toFixed(2);
        this.addGoodItem.serverList.push(item);
      }

      this.jishuanTotal();
    },

    addItemCancle() {
      this.resetFormData("addItemForm");

      this.addItemObj = {
        clockType: "",
        contentCount: 1,
        contentId: "",
        contentType: "",
        orderId: "",
        userId: "",
      };
      this.$nextTick(() => {
        this.addItemVis = false;
        this.addItemLoading = false;
      });
    },
    changeServeTh() {
      let array = [];
      let thObj = this.thArryObj[this.addItemObj.userId];
      this.addItemObj.clockType = "";
      // 技师是否在本订单中 本订单只能加钟 yn
      if (!!thObj && thObj.userStatus === "Y") {
        array = [
          {
            label: "加钟",
            value: "A",
          },
        ];
      } else {
        array = [
          {
            label: "轮钟",
            value: "F",
          },
          {
            label: "点钟",
            value: "P",
          },
          {
            label: "约客",
            value: "V",
          },
          {
            label: "加班",
            value: "W",
          },
        ];
      }

      this.clockTypeList = array;
    },
    addItemCancle() {
      this.resetFormData("addItemForm");

      this.addItemObj = {
        clockType: "",
        contentCount: 1,
        contentId: "",
        contentType: "",
        orderId: "",
        userId: "",
      };
      this.$nextTick(() => {
        this.addItemVis = false;
        this.addItemLoading = false;
      });
    },

    // 表单重置
    resetFormData(formName) {
      this.$refs[formName].resetFields();
    },

    itemAddOpen(row) {
      this.setUserItem(row, "I");
      this.getTharry(row.itemId);
      this.getsellUserId();
    },

    goodsAddOpen(row) {
      this.setUserItem(row, "P");
    },

    setUserItem(row, contentType) {
      console.log("like", row);
      this.clockTypeList = [];
      this.addItemObj = {
        clockType: "",
        contentCount: 1,

        contentId:
          contentType === "I"
            ? row.itemId
            : contentType === "P"
            ? row.productId
            : "",
        contentType: contentType,
        orderId: this.addGoodItem.orderId,
        userId: "",

        contentName: row.itemName || row.name,
        price:
          contentType === "I"
            ? row.itemPrice
            : contentType === "P"
            ? row.price
            : 0,
      };

      this.addItemVis = true;
    },
    goodsAddOpen(row) {
      this.setUserItem(row, "P");
    },
    addXfSave() {
      if (
        (!!this.addGoodItem.serverList &&
          this.addGoodItem.serverList.length === 0) ||
        Number(this.serverTotal) === 0
      ) {
        this.$message.error("暂无新增的项目或商品");
        return false;
      }
      console.log(this.addGoodItem);
      this.$emit("addConsume", this.addGoodItem);

      setTimeout(() => {
        this.addGoodCancle();
      }, 200);

      //   if (this.addGoodLoading) {
      //     return false;
      //   }

      //   this.addGoodLoading = true;
      //   const { orderId } = this.addGoodItem;
      //   orderCreateServer(this.addGoodItem)
      //     .then((res) => {
      //       this.addGoodLoading = false;
      //       const { code, data } = res;
      //       if (code === 0) {
      //         this.$message({
      //           type: "success",
      //           message: "操作成功!",
      //         });
      //
      //         this.getRoomList();
      //       }
      //     })
      //     .catch((err) => {
      //       this.addGoodLoading = false;
      //     });
    },

    addGoodCancle() {
      this.addGoodVis = false;
      this.serverTotal = "0.00";
      this.addGoodLoading = false;
      this.addGoodItem = {
        // orderId: "",
        serverList: [],
      };
    },

    handleClick() {
      if (this.activeName === "0") {
        this.getItemAllList();
      } else if (this.activeName === "1") {
        this.shopProductQuery.pageNo = 1;
        this.getProductAllList();
      }
    },

    getItemAllList() {
      this.shopItemLoading = true;
      itemAllList({
        sellStatus: 0,
      })
        .then((res) => {
          console.log(res);
          this.shopItemLoading = false;
          const { code, data } = res;
          if (code === 0) {
            this.shopItemArray = data;
          }
        })
        .catch((err) => {
          this.shopItemLoading = false;
        });
    },

    // 新增消费
    openAdddGood(data) {
      this.addGoodVis = true;
      this.serverTotal = "0.00";
      this.addGoodLoading = false;
      this.addGoodItem = {
        orderId: !!data ? data.orderId : "",
        roomId: !!data ? data.roomId : "",
        serverList: [],
      };
      this.activeName = "0";
      this.getItemAllList();
    },

    getProductAllList() {
      this.shopProductLoading = true;
      getProductList({
        pageNo: this.shopProductQuery.pageNo,
        pageSize: this.shopProductQuery.pageSize,
        sellStatus: 0,
      })
        .then((res) => {
          console.log(res);
          this.shopProductLoading = false;
          const { code, data } = res;
          if (code === 0) {
            this.shopProductArray = data.list;
            this.shopProductQuery.total = data.total;
          }
        })
        .catch((err) => {
          this.shopProductLoading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.add {
  .item-list {
    height: 400px;
    overflow: auto;
    .item-list-row {
      width: 100%;
      overflow: hidden;
    }
    .item-xf {
      height: 98px;
      background-color: #f7f8fa;
      border-radius: 12px;
      padding: 24px;
      margin-bottom: 24px;
      cursor: pointer;
      &:hover {
        opacity: 0.8;
      }
      .item-name {
        font-size: 16px;
        font-weight: bold;
      }

      .item-price {
        font-size: 12px;
        margin-top: 12px;
      }
    }
  }

  .right-ck-list {
    padding-top: 40px;
    .ck-price {
      color: #ff4040;
      font-size: 14px;
    }

    .right-ck-bootom {
      height: 54px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
}
</style>
